/*

5 5
S****
*****
...**
*****
*C***

5 5
S****
...**
C**.*
*.***
**...

 */
package com.yuan.algorithms.arithmetic_2;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

class Node{
	int len;//路径长度
	int x;
	int y;

	public Node(int len, int x, int y) {
		this.len = len;
		this.x = x;
		this.y = y;
	}
}

public class BFS_最短路径 {

	static final int[] var = {1,0,0,1,-1,0,0,-1};
	static char[][] map;
	static int[][] mark;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			int n = sc.nextInt();
			int m = sc.nextInt();
			map = new char[n+2][m+2];//地图预定义大一圈，用于防止下标越界
			mark = new int[n+2][m+2];//标记数组，用于标记该地点是否被搜索过
			int[] start = new int[2];//起点坐标
			for (int i = 0; i < n; i++) {
				String s = sc.next();
				for (int j = 0; j < m; j++) {
					//获得起点坐标
					if (s.charAt(j) == 'S') {
						start[0] = j+1;//x
						start[1] = i+1;//y
					}
					map[j+1][i+1] = s.charAt(j);
				}
			}
			System.out.println(BFS(start));
		}
	}

	private static int BFS(int[] start) {
		Queue<Node> queue = new LinkedList<Node>();
		Node k = new Node(0, start[0], start[1]);
		queue.add(k);
		while (!queue.isEmpty()) {
			Node temp = queue.poll();
			if (map[temp.x][temp.y] == 'C') {
				return temp.len;
			}
			//按右、下、左、上的顺序搜索地图
			for (int i = 0; i < 4; i++) {
				int tx = temp.x+var[i*2];
				int ty = temp.y+var[i*2+1];
				if ((map[tx][ty] == '*' || map[tx][ty] == 'C') && mark[tx][ty]!=1) {
					queue.add(new Node(temp.len+1, tx, ty));
					mark[tx][ty] = 1;
				}
			}
		}
		return -1;
	}

}
